<?php

/**
 * Description of G_Pdo
 *
 * @author Monk <eoe2005@gmail.com>
 */
if (class_exists('PDO') === false) {
    trigger_error('系统不支持PDO');
    die();
}

class G_Pdo extends GC_Db {

    protected $_pdo;
    protected $_res;

    public function __construct($conf) {
        if (isset($conf['dbtype']) AND isset($conf['host']) AND isset($conf['username']) AND isset($conf['passwd']) AND isset($conf['dbname'])) {
            try {
                $this->_pdo = new PDO($conf['dbtype'] . ':dbname=' . $conf['dbname'] . ';host=' . $conf['host'], $conf['username'], $conf['passwd']);
            } catch (PDOException $e) {
                trigger_error($e->getMessage());
            }die();
        } else {
            trigger_error('参数错误');
            die();
        }
    }

    public function affectedRows() {
        return $this->_res;
    }

    public function begin() {
        return $this->_pdo->beginTransaction();
    }

    public function commit() {
        return $this->_pdo->commit();
    }

    public function escape($str) {
        return $this->_res = $this->_pdo->quote($str);
    }

    public function exec($sql) {
        $this->_res = $this->_pdo->exec($sql);
        return $this->_res;
    }

    public function getLastId() {
        return $this->_pdo->lastInsertId();
    }

    public function getResults($sql) {
        $res = $this->query($sql);
        return $res->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getRow($sql) {
        $res = $this->query($sql);
        if ($res) {
            $row = $res->fetch(PDO::FETCH_ASSOC);
            return $row;
        }
        return null;
    }

    public function getVar($sql) {
        $row = $this->getRow($sql);
        if ($res) {
            $row = $res->fetch();
            foreach ($res AS $val) {
                return $val;
            }
        }
        return null;
    }

    public function query($sql) {
        return $this->_pdo->query($sql);
    }

    public function rollback() {
        return $this->_pdo->rollBack();
    }

}
